//
//  ExampleSearchView.m
//  NekaPrice
//
//  Created by yu on 2018/6/22.
//  Copyright © 2018年 ma c. All rights reserved.
//

#import "ExampleSearchView.h"
static NSString *const kCellID = @"CellID";

static CGFloat kMenuHeight = 35.0;
static CGFloat kDuration = 0.3;

@interface ExampleSearchView()<UITextFieldDelegate>
@property (nonatomic, assign)CGFloat firstHeight;
@property (nonatomic, assign)CGFloat secondHeight;
@property (nonatomic, strong)UIButton *menuBtn;
@end

@implementation ExampleSearchView

- (instancetype)initAndSearchTextInCenter:(BOOL)inCenter {
    if (self = [super init]) {
        
        self.firstHeight = 120;
        self.secondHeight = 240;
        
        [self addSubview:self.searchText];
        if (inCenter) {
            
            [self.searchText mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(kMenuHeight);
                make.left.mas_equalTo(60);
                make.right.mas_equalTo(-60);
                make.centerX.mas_equalTo(self.mas_centerX);
                make.bottom.mas_equalTo(-5);
                
            }];
            self.searchText.clearButtonMode = UITextFieldViewModeAlways;
        }else {
            [self addSubview:self.menuBtn];
            [self.menuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(kMenuHeight - 10);
                make.right.mas_equalTo(-10);
                make.bottom.mas_equalTo(-8);
            }];
            
            NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
            CGFloat leftWidth = [@"搜索" widthWithFixedHeight:kMenuHeight andEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 10) attributes:attributes];
            CGFloat rightWidth = [@"案例查找" widthWithFixedHeight:kMenuHeight andEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 10) attributes:attributes];
            
            [self.searchText mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(kMenuHeight);
                if (kIsiPad) {
                    make.width.mas_equalTo((kContentView_WIDTH - 40) / 3 * 2 + 10);
                }else {
                    make.width.mas_equalTo((K_WIDTH - 40) / 3 * 2 + 10);
                }
                make.left.mas_equalTo(10);
                make.bottom.mas_equalTo(-5);
            }];
    
        }
    }
    return self;
}

- (UIButton *)menuBtn {
    if (_menuBtn == nil) {
        _menuBtn = [[UIButton alloc] init];
        [_menuBtn setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
        _menuBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_menuBtn addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _menuBtn;
}



- (UITextField *)searchText {
    if (_searchText == nil) {
        
        NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
        CGFloat leftWidth = [@"搜索" widthWithFixedHeight:kMenuHeight andEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 10) attributes:attributes];
        
        UIColor *borderColor = [UIColor colorWithHexString:@"#0374e7"];
        
        UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, leftWidth, kMenuHeight)];
        rightBtn.layer.masksToBounds = YES;
        rightBtn.layer.cornerRadius = 3;
        [rightBtn setTitle:@"搜索" forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [attributes objectForKey:NSFontAttributeName];
        rightBtn.backgroundColor = [UIColor colorWithHexString:@"#0374e7"];
        [rightBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
        
        _searchText = [[UITextField alloc] init];
        _searchText.delegate = self;
        _searchText.layer.cornerRadius = 3;
        _searchText.layer.masksToBounds = YES;
        _searchText.layer.borderColor = borderColor.CGColor;
        _searchText.layer.borderWidth = 1.0f;
        _searchText.leftViewMode = UITextFieldViewModeAlways;
        _searchText.rightViewMode = UITextFieldViewModeAlways;
        _searchText.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, kMenuHeight)];
        _searchText.rightView = rightBtn;
        _searchText.returnKeyType = UIReturnKeySearch;
        _searchText.font = [attributes objectForKey:NSFontAttributeName];
        _searchText.placeholder = @"案例查找";
    }
    return _searchText;
}

#pragma mark -- TextField代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (_searchText.text.length > 0) {
        if (_searchBlock) {
            _searchBlock(_searchText.text);
        }
    }else {
        [MBProgressHUD showError:@"请输入内容!" toView:[UIApplication sharedApplication].keyWindow];
    }
    return YES;
}


//移动搜索框到中间,隐藏菜单按钮
- (void)moveSearchTextToCenter {
    [_menuBtn setHidden:YES];
    
    [_searchText mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.rightMargin.mas_equalTo(60);
        make.centerX.mas_equalTo(self.mas_centerX);
        make.centerY.mas_equalTo(self.mas_centerY);
    }];
}



- (UITableView *)firstTableView {
    if (_firstTableView == nil) {
        _firstTableView = [[UITableView alloc] initWithFrame:CGRectMake(K_WIDTH / 2, self.y + self.height, K_WIDTH / 2, self.firstHeight) style:UITableViewStylePlain];
        _firstTableView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.9];
        _firstTableView.delegate = self;
        _firstTableView.dataSource = self;
        _firstTableView.separatorColor = [UIColor whiteColor];
        [_firstTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellID];
    }
    return _firstTableView;
}

- (UITableView *)secondTableView {
    if (_secondTableView == nil) {
        _secondTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.y + self.height, K_WIDTH / 2, self.secondHeight) style:UITableViewStylePlain];
        _secondTableView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.9];
        _secondTableView.delegate = self;
        _secondTableView.dataSource = self;
        _secondTableView.separatorColor = [UIColor whiteColor];
        [_secondTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellID];
        
        _secondTableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
        [_secondTableView addSubview:self.backBtn];
    }
    return _secondTableView;
}

- (void)openMenu:(UIButton *)btn {
    if (self.firstTableView.superview == nil && self.secondTableView.superview == nil) {
        [self showFirstTableView];
    }else {
        [self hideFirstTableView];
        [self hideSecondTableView];
    }
}

- (CGFloat)firstHeight {
    return self.firstList.count * 40;
}

- (CGFloat)secondHeight {
    CGFloat height = (self.secondList.count + 1) * 40;
    return height > 360 ? 360 : height;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.firstTableView) {
        return _firstList.count;
    }else {
        return _secondList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (tableView == self.firstTableView) {
        CategoryModel *model = _firstList[indexPath.row];
        cell.textLabel.text = model.name;
    }else {
        CategoryListModel *model = self.secondList[indexPath.row];
        cell.textLabel.text = model.name;
    }
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (tableView == self.firstTableView) {
        CategoryModel *model = self.firstList[indexPath.row];
        self.secondList = model.categoryList;
        [self hideFirstTableView];
        [self.secondTableView reloadData];
        [self showSecondTableView];
    }else {
        [self hideSecondTableView];
        CategoryListModel *model = self.secondList[indexPath.row];
        if (_selectedBlock) {
            _selectedBlock(model.url);
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}




//显示/隐藏

#pragma mark -- 显示一级分类
- (void)showFirstTableView {
    [self.superview addSubview:self.firstTableView];
    self.firstTableView.alpha = 0;
    self.firstTableView.transform = CGAffineTransformMake(0.8, 0, 0, 0.8, 0, 0);
    [UIView animateWithDuration:kDuration animations:^{
        self.firstTableView.transform = CGAffineTransformIdentity;
        self.firstTableView.alpha = 1;
    }];
}
#pragma mark -- 隐藏一级分类
- (void)hideFirstTableView {
    self.firstTableView.alpha = 1;
    
    [UIView animateWithDuration:kDuration animations:^{
        self.firstTableView.transform = CGAffineTransformMake(0.8, 0, 0, 0.8, 0, 0);
        self.firstTableView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.firstTableView removeFromSuperview];
        self.firstTableView.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark -- 显示二级分类
- (void)showSecondTableView {
    self.secondTableView.frame = CGRectMake(0, self.y + self.height, K_WIDTH / 2, self.secondHeight);
    [self.superview addSubview:self.secondTableView];
    self.secondTableView.alpha = 0;
    [UIView animateWithDuration:kDuration animations:^{
        self.secondTableView.alpha = 1;
        self.secondTableView.frame = CGRectMake(K_WIDTH / 2, self.y + self.height, K_WIDTH / 2, self.secondHeight);
    }];
}

#pragma mark -- 隐藏二级分类
- (void)hideSecondTableView {
    self.secondTableView.alpha = 1;
    
    [UIView animateWithDuration:kDuration animations:^{
        self.secondTableView.frame = CGRectMake(0, self.y + self.height, K_WIDTH / 2, self.secondHeight);
        self.secondTableView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.secondTableView removeFromSuperview];
    }];
}


- (void)setFirstList:(NSArray *)firstList {
    _firstList = firstList;
    [self.firstTableView reloadData];
}


- (UIButton *)backBtn {
    if (_backBtn == nil) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, -40, K_WIDTH / 2, 40)];
        _backBtn.backgroundColor = [UIColor clearColor];
        [_backBtn setTitle:@"返回上一级" forState:UIControlStateNormal];
        [_backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (void)backAction:(UIButton *)btn {
    [self hideSecondTableView];
    [self showFirstTableView];
}


- (void)searchAction:(UIButton *)btn {
    if (_searchBlock) {
        _searchBlock(_searchText.text);
    }
}

#pragma mark -- cell的分割线宽度等于屏幕宽度
-(void)viewDidLayoutSubviews {
    
    if ([self.firstTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.firstTableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.firstTableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.firstTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([self.secondTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.secondTableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.secondTableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.secondTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


- (void)hideAllViews {
    [self hideFirstTableView];
    [self hideSecondTableView];
}

@end
